﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using HCRS.Errors;

namespace JinJiang.BookingEngine.Web.cn
{
    public class FGBCommon
    {
        private static string iv = "field.kang";
        private static string key = "hubs1.net";

        public static string CreatePassWord(int Len)
        {
            var password = "";
            var word = new[]
                           {
                               "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
                           };
            var Max = word.Length;
            var R = new Random(DateTime.Now.Millisecond);
            for (var i = 0x0; i < Len; i++)
            {
                password = password + word[R.Next(Max)];
            }
            return password;
        }

        public static string Decrypt(string strText, string strKey, string strIV)
        {
            strKey = strKey + "field.kang";
            byte[] byKey = null;
            var IV = Encoding.ASCII.GetBytes(strIV);
            var inputByteArray = new byte[strText.Length];
            try
            {
                byKey = Encoding.UTF8.GetBytes(strKey.Substring(0x0, 0x8));
                var des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0x0, inputByteArray.Length);
                cs.FlushFinalBlock();
                Encoding encoding = new UTF8Encoding();
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception)
            {
                return "";
            }
        }

        public static string Encrypt(string strText, string strKey, string strIV)
        {
            strKey = strKey + "field.kang";
            byte[] byKey = null;
            var IV = Encoding.ASCII.GetBytes(strIV);
            try
            {
                byKey = Encoding.UTF8.GetBytes(strKey.Substring(0x0, 0x8));
                var des = new DESCryptoServiceProvider();
                var inputByteArray = Encoding.UTF8.GetBytes(strText);
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0x0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception)
            {
                return "";
            }
        }

        internal static string GetaddMD5(string str)
        {
            var addMD5 = new MD5CryptoServiceProvider();
            return Encoding.ASCII.GetString(addMD5.ComputeHash(Encoding.ASCII.GetBytes(HttpContext.Current.Server.MachineName + str)));
        }

        public static string GetConfiguration(string key)
        {
            return GetConfiguration(key, "");
        }

        public static string GetConfiguration(string key, string defalut)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch
            {
                return defalut;
            }
        }

        public static object IsNull(object o, Type type)
        {
            if ((o == null) || (o.GetType() == typeof (DBNull)))
            {
                if (type == typeof (int))
                {
                    return 0x0;
                }
                if (type == typeof (DateTime))
                {
                    return new DateTime();
                }
                if (type == typeof (bool))
                {
                    return false;
                }
                if (type == typeof (string))
                {
                    return string.Empty;
                }
                if (type == typeof (byte))
                {
                    return (byte) 0x0;
                }
                if (type == typeof (decimal))
                {
                    return 0M;
                }
                if (type == typeof (double))
                {
                    return 0.0;
                }
            }
            return o;
        }

        public static string ReadFile(string path)
        {
            try
            {
                var sr = File.OpenText(path);
                var Content = sr.ReadToEnd();
                sr.Close();
                sr = null;
                return Content;
            }
            catch (Exception)
            {
                return "文件不存在！";
            }
        }

        public static bool SendEMail(string mailto, string subject, string Content, out string msg)
        {
            var mailserver = ConfigurationManager.AppSettings["mailserver"];
            var mailuser = ConfigurationManager.AppSettings["mailuser"];
            var mailpwd = ConfigurationManager.AppSettings["mailpwd"];
            var mailfrom = "常客系统";
            var usermail = mailuser;
            var body = Content;
            return SendMail(mailto, "", usermail, mailfrom, subject, body, mailserver, mailuser, mailpwd, out msg);
        }

        public static bool SendEMail(string mailto, string emailalias, string mailfrom, string subject, string Content, out string msg)
        {
            var mailserver = ConfigurationManager.AppSettings["mailserver"];
            var mailuser = ConfigurationManager.AppSettings["mailuser"];
            var mailpwd = ConfigurationManager.AppSettings["mailpwd"];
            var body = Content;
            return SendMail(mailto, "", mailfrom, emailalias, subject, body, mailserver, mailuser, mailpwd, out msg);
        }

        public static bool SendMail(string mailTo, string cc, string mailFrom, string alias, string subject, string body, string mailServer, string user, string password, out string msg)
        {
            try
            {
                var client = new SmtpClient(mailServer)
                                 {
                                     UseDefaultCredentials = false,
                                     Credentials = new NetworkCredential(user, password),
                                     DeliveryMethod = SmtpDeliveryMethod.Network
                                 };
                var MailFrom = new MailAddress(mailFrom, alias);
                var message = new MailMessage
                                  {
                                      From = MailFrom
                                  };
                var tempTo = mailTo.Split(new[]
                                              {
                                                  ','
                                              });
                for (var i = 0x0; i < tempTo.Length; i++)
                {
                    message.To.Add(tempTo[i]);
                }
                message.Subject = subject;
                message.Body = body;
                message.Priority = MailPriority.High;
                message.BodyEncoding = Encoding.UTF8;
                message.IsBodyHtml = true;
                client.Send(message);
                msg = "Email 发送成功";
                return true;
            }
            catch (Exception ex)
            {
                msg = "fail：" + ex.Message;
                return false;
            }
        }

        public static string WebDomain(bool ispost, out string domainurl)
        {
            var domain = "";
            domainurl = "";
            try
            {
                if (HttpContext.Current.Request.UrlReferrer != null)
                {
                    if (HttpContext.Current.Request.UrlReferrer.Host == HttpContext.Current.Request.Url.Host)
                    {
                        if (ispost)
                        {
                            domainurl = HttpContext.Current.Request.Form.Get("wd");
                        }
                        else
                        {
                            domainurl = HttpContext.Current.Request.Params.Get("wd");
                        }
                        if (domainurl != null)
                        {
                            return Decrypt(domainurl, key, iv);
                        }
                    }
                    domain = HttpContext.Current.Request.UrlReferrer.AbsoluteUri;
                }
                if (domain.Length > 0xa)
                {
                    domain = domain.Substring(0x0, domain.IndexOf("/", 0x8));
                    domainurl = Encrypt(domain, key, iv);
                }
                return domain;
            }
            catch (Exception e)
            {
                WebError.SendErrorEmail(e);
                return domain;
            }
        }

        public static string GetGuaImage(string gua)
        {
            string str = "";
            if (gua.IndexOf("PP") >= 0)
            {
                return "<img src=\"images/money.gif\" width=\"11\" height=\"11\" title=\"本房型需预付保证\" />";
            }
            if (gua.IndexOf("CC") >= 0)
            {
                str = "<img src=\"images/visa.gif\" width=\"11\" height=\"11\" title=\"本房型需信用卡担保\" />";
            }
            if (gua.IndexOf("DP") >= 0)
            {
                str = "<img src=\"images/visa.gif\" width=\"11\" height=\"11\" title=\"本房型需信用卡担保\" />";
            }
            return str;
        }
    }
}